package com.yx.cloud.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.iot.product.sweeper.bean.BaseStation;


public class GradientBackgroundView extends View {
    LinearGradient linearGradient;

    int mode;
    float[] hsv;
    Paint paint;

    public GradientBackgroundView(Context context) {
        super(context);
        init();
    }

    public GradientBackgroundView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);
        hsv = new float[]{0, 1, 1};
    }

    public void setColor(int mode) {
        this.mode = mode;
        linearGradient = null;
        postInvalidate();
    }

    public void setColor(float[] hsv, int mode) {
        this.mode = mode;
        this.hsv = hsv;
        linearGradient = null;
        postInvalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth();
        int height = getHeight();
        if (linearGradient == null) {
            if (mode == BaseStation.LIGHT_TYPE_WHITE) {
                int color = Color.HSVToColor(new float[]{37, (1 - hsv[2]) * 0.5f + 0.08f, 1});
                linearGradient = new LinearGradient(0, 0, width, 0, new int[]{color, color}, null, Shader.TileMode.CLAMP);
            } else if (mode == BaseStation.LIGHT_TYPE_COLORFUL) {
                float s=hsv[1]/2+0.5f;
                float b=hsv[2]/2+0.5f;
                linearGradient = new LinearGradient(0, 0, width, 0, new int[]{
                        Color.HSVToColor(new float[]{hsv[0], s - 0.2f > 0 ? s - 0.2f : 0, b}),
                        Color.HSVToColor(new float[]{hsv[0], s - 0.38f > 0 ? s - 0.38f : 0, b}),
                        Color.HSVToColor(new float[]{(hsv[0] + 33) > 360 ? 0 : (hsv[0] + 33), s - 0.48f > 0 ? s - 0.48f : 0, b}),
                        Color.HSVToColor(new float[]{(hsv[0] + 33) > 360 ? 0 : (hsv[0] + 33), s - 0.2f > 0 ? s - 0.2f : 0, b}),
                        Color.HSVToColor(new float[]{hsv[0], s, b})
                }, null, Shader.TileMode.CLAMP);
            } else if (mode == BaseStation.LIGHT_TYPE_RAINBOW) {
                linearGradient = new LinearGradient(0, 0, width, 0, new int[]{0xffFF7F7F, 0xffF59DF5, 0xff99B8FF, 0xff7FFFFF, 0xff8EFB8E, 0xffF5EA7D, 0xffFF7F7F}, null, Shader.TileMode.CLAMP);
            }
        }

        paint.setShader(linearGradient);
        canvas.drawRect(0, 0, width, height, paint);

    }
}
